<?php
Yii::import('zii.widgets.jui.CJuiInputWidget');

class JMerchantSelector extends CJuiInputWidget {
	public $relatedAttribute;
	public $unselectedMessage = '未选择';
	public $selectedMessage = '已选择 {name}';
	/**
	 * js string: function(merchantId){}
	 */
	public $onSelectCallback;

	public function run() {
		list($name, $id) = $this->resolveNameID();

		if (isset($this->htmlOptions['id']))
			$id = $this->htmlOptions['id'];
		else
			$this->htmlOptions['id'] = $id;

		if (isset($this->htmlOptions['name']))
			$name = $this->htmlOptions['name'];

		if ($this->hasModel()) {
			echo CHtml::activeHiddenField($this->model, $this->attribute, $this->htmlOptions);
		} else
			echo CHtml::hiddenField($name, $this->value, $this->htmlOptions);

		$textId = $id . '_merchant_input';
		echo CHtml::textField($id . '_merchant_input', '',
			CMap::mergeArray($this->htmlOptions, array(
				'id' => $textId
			)));
		$spanId = $id . '_merchant_display';
		$spanContent = '';
		if ($this->relatedAttribute && ($merchantModel = $this->model->{$this->relatedAttribute})) {

			$spanContent = strtr($this->selectedMessage,
				array(
					'{name}' => $merchantModel->name
				));
		} elseif ($this->model->{$this->attribute}) {
			$merchantModel = Merchant::model()->findByPk($this->model->{$this->attribute});
			if ($merchantModel) {
				$spanContent = strtr($this->selectedMessage, '{name}', $merchantModel->name);
			}
		} else {
			$spanContent = $this->unselectedMessage;
		}

		echo ' ';
		echo CHtml::tag('span', array(
			'id' => $spanId
		), $spanContent);
		echo ' ';
		echo CHtml::link('清除', '#',
			array(
				'onclick' => '$("#' . $id . '").val("");
								$("#' . $spanId . '").html('
					. CJavaScript::encode($this->unselectedMessage) . ');',
			));

		$this->options['source'] = Yii::app()->controller->createUrl('/merchant/search');
		$this->options['minLength'] = '2';
		$callback = '';
		if ($this->onSelectCallback) {
			$callback='('.$this->onSelectCallback.')(ui.item.id);';
		}
		$this->options['select'] = 'js:function(event,ui) {
								$("#' . $id . '").val(ui.item.id);
								$("#' . $spanId . '").html('
			. CJavaScript::encode($this->selectedMessage)
			. '.replace("{name}",ui.item.label));
			'.$callback.'}';
		$options = CJavaScript::encode($this->options);

		$js = "jQuery('#{$textId}').autocomplete($options);";

		$cs = Yii::app()->getClientScript();
		$cs->registerScript(__CLASS__ . '#' . $id, $js);
	}
}
